import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/mixin/refresh_mixin.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/lottie_utils.dart';
import 'package:url_launcher/url_launcher.dart';

class HomeLogic extends GetxController with RefreshMixin {
  final TextEditingController searchController = TextEditingController();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    LottieUtils.showToastLoading();
    onRefresh();
    bus.on('network_refresh', (value) {
      onRefresh();
    });
    bus.on('code_update', (value) {
      onRefresh();
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  @override
  Future<void> onRefresh() async {
    await getIndexData();
    super.onRefresh();
  }

  /// 获取秒杀商品
  List zeroProductList = [];

  ///获取热门分类
  List hotCategoryList = [];

  ///首页店铺数据
  List frontShopList = [];

  ///获取分类商品
  List categoryProductList = [];

  ///首页数据新接口
  Future<void> getIndexData() async {
    BaseResponse response = await ProductApi.getIndexData();
    if (response.isSuccess) {
      zeroProductList = response.data['zeroAndDiscountList'] ?? [];
      hotCategoryList = response.data['categoryList'] ?? [];
      frontShopList = response.data['shopList'] ?? [];
      categoryProductList = response.data['categoryProductList'] ?? [];
      update();
    }
    LottieUtils.hideToastLoading();
  }

  /// 搜索
  void onSearchClick() async {
    searchController.text = searchController.text.trim();
    if (searchController.text.isEmpty) {
      return;
    }

    ///判断是否包含链接
    if (hasLink(searchController.text)) {
      List<String> links = extractLinks(searchController.text);
      if (links.isNotEmpty) {
        //解析链接
        String link = links[0];
        BaseResponse response = await ProductApi.resolveUrl(link);
        if (response.isSuccess) {
          Map<String, dynamic> data = response.data ?? {};
          String url = data['url'] ?? '';
          launchUrl(Uri.parse('${AppPrefix.urlPrefix}/product-detail?url=${Uri.encodeComponent(url)}'));
        }
      }
      return;
    }

    RouteUtils.toSearch(keyword: searchController.text);
  }

  //判断内容中是否包含链接
  static bool hasLink(String content) {
    final RegExp linkRegExp = RegExp(r'(https?:\/\/|itaobuy:\/\/)[^\s]+');
    return linkRegExp.hasMatch(content);
  }

  //提取内容中的链接
  static List<String> extractLinks(String content) {
    final RegExp linkRegExp = RegExp(r'(https?:\/\/|itaobuy:\/\/)[^\s]+');
    Iterable<Match> matches = linkRegExp.allMatches(content);
    return matches.map((match) => match.group(0)!).toList();
  }
}
